<?php
/**
 * Name: 帮助函数类.
 * User: Small_K
 * Date: 2018/1/11
 * Time: 15:27
 */

namespace App\Services\Tool;

/**
 * Class Help
 * @package App\Services\Tool
 *
 * 帮助函数类
 * 注意: 定义时直接定义public static function
 * <code>
 *   public static function some_public_method($a)
 * </code>
 * 此类已在 config/app.php 中aliases数组中注册
 *
 * 代码中的调用方法:
 * <code>
 *   Helper::some_public_method($a);
 * </code>
 */

class Helper
{
    /**
     *
     * 随机生成数字+字母组合的字符串
     *
     * <h2>Helper::createRandomStr</h2>
     * <code>
     *   $filter = Helper::createRandomStr();
     * </code>
     * @param int $len 长度
     *
     * @return array|string
     */
    public static function createRandomStr($len)
    {
        $str = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
        shuffle($str);
        $str = implode('', array_slice($str, 0, $len));
        return $str;
    }

    /**
     *
     * 获取过滤数组
     *
     * <h2>Helper::getFilter</h2>
     * <code>
     *   $filter = Helper::getFilter();
     * </code>
     * @param null $filter
     * @return array|mixed 返回过滤信息数组, 如无过滤信息则返回空数组
     */
    public static function getFilter($filter = null)
    {
        // 前端传递的参数会把末尾的==给删除, 转码前必须加上。
        $raw = is_null($filter) ? request('f', '') . '==' : $filter;
        if (!empty($raw)) {
            if (strpos($raw, ' ') !== false) {
                $raw = str_replace(' ', '+', $raw);
            }
            $json_str = urldecode(base64_decode($raw));
            return json_decode($json_str, true);
        }
        return [];
    }

    /**
     *
     * 获取排序数组
     *
     * @param null $filter
     * @return array|mixed
     */
    public static function getSorts($filter = null)
    {
        $raw = is_null($filter) ? request('s', '') . '==' : $filter;
        if (!empty($raw)) {
            if (strpos($raw, ' ') !== false) {
                $raw = str_replace(' ', '+', $raw);
            }
            $json_str = urldecode(base64_decode($raw));
            $data = json_decode($json_str, true);
            if (!is_null($data)) {
                foreach ($data as $key => $value) {
                    if ($value == 1) {
                        $data[$key] = 'ASC';
                    } elseif ($value == -1) {
                        $data[$key] = 'DESC';
                    } else {
                        $data['id'] = 'ASC';
                    }
                }
            }
            return $data;
        }
        return [];
    }

    /**
     *
     * 编码转换
     *
     * <h2>Helper::transCoding</h2>
     * <code>
     *   $filter = Helper::transCoding();
     * </code>
     * @param $string
     * @param bool $out_put
     * @param null $type
     * @return mixed|string
     */
    public static function transCoding($string, $out_put = true, $type = null)
    {
        $system = $type ? $type : substr(PHP_OS, 0, 3);
        if ($system === 'WIN') {
            if ($out_put) {
                return mb_convert_encoding($string, 'GBK', 'UTF-8');
            } else {
                return mb_convert_encoding($string, 'UTF-8', 'GBK');
            }
        }
        return $string;
    }

    /**
     *
     * 判断是否为手机端
     *
     * @return bool
     */
    public static function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])) {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }

    /**
     *
     * 判断是否为微信浏览器
     *
     * @param Request $request
     * @return bool
     */
    public static function isWechatClient(Request $request)
    {
        return strpos($request->header('user_agent'), 'MicroMessenger') !== false;
    }

    /**
     *
     * 判断手机号码是否正确
     *
     * @param $mobile
     * @return bool
     */
    public static function checkMobileValid($mobile)
    {
        if (!preg_match('/^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17([0,5-8]))|(18[0-9]))\\d{8}$/', $mobile)) {
            return false;
        }
        return true;
    }

    /**
     *
     * 裁剪生成新图片
     *
     * @param $filename //目标文件名
     * @param $image_src //原始文件
     * @param $data //裁剪数据 x y width height
     * @param int $quality //保存质量默认100
     * @return bool
     */
    public static function createNewImage($filename, $image_src, $data, $quality = 9)
    {
        $data = json_decode($data, true);
        $source_info = getimagesize($image_src);
        $source_width = $source_info[0];
        $source_height = $source_info[1];
        $source_mime = $source_info['mime'];
        $source_ratio = $source_height / $source_width;

        $target_ratio = $data['height'] / $data['width'];

        // 源图过高
        if ($source_ratio > $target_ratio) {
            $cropped_width = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            $source_y = ($source_height - $cropped_height) / 2;
        } elseif ($source_ratio < $target_ratio) {// 源图过宽
            $cropped_width = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
        } else {// 源图适中
            $cropped_width = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }

        switch ($source_mime) {
            case 'image/gif':
                $source_image = imagecreatefromgif($image_src);
                break;

            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($image_src);
                break;

            case 'image/png':
                $source_image = imagecreatefrompng($image_src);
                break;

            default:
                return false;
                break;
        }

        $target_image = imagecreatetruecolor($data['width'], $data['height']);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);

        // 裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $data['width'], $data['height'], $cropped_width, $cropped_height);

        $success = imagepng($target_image, $filename, $quality);
        imagedestroy($target_image);
        imagedestroy($source_image);
        imagedestroy($cropped_image);
        return $success;
    }

    /**
     *
     * 从Ip地址获取城市信息
     *
     * @param $ip
     * @return bool|mixed
     */
    public static function getCityFromIp($ip)
    {
        $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
        if (empty($res)) {
            return false;
        }
        $jsonMatches = array();
        preg_match('#\{.+?\}#', $res, $jsonMatches);
        if (!isset($jsonMatches[0])) {
            return false;
        }
        $json = json_decode($jsonMatches[0], true);
        if (isset($json['ret']) && $json['ret'] == 1) {
            $json['ip'] = $ip;
            unset($json['ret']);
        } else {
            return false;
        }
        return $json;
    }

    /**
     *
     * 获取秒到时间
     *
     * @param $times //时间，单位 秒
     * @return string
     */
    public static function getSecToTime($times)
    {
        $result = '00:00:00';
        if ($times > 0) {
            $hour = floor($times / 3600);
            $minute = floor(($times - 3600 * $hour) / 60);
            $second = floor((($times - 3600 * $hour) - 60 * $minute) % 60);
            $result = $hour . ':' . $minute . ':' . $second;
        }
        return $result;
    }

}